# -*- coding: utf-8 -*-
import json
from datetime import datetime

# from common.utils import tz


def parse_query(query_dct):
    query_cond = dict()
    for k, v in query_dct.items():
        if not isinstance(v, basestring):
            query_cond.update({k: v})
            continue
        if k == '_':
            continue
        if k.startswith('$'):
            continue
        if v.startswith('{') or v.startswith('['):
            print v
            v = json.loads(v)
            c1 = dict()
            if isinstance(v, dict):
                for k1, v1 in v.items():
                    if k1 in ('$gte', '$lte', '$gt', '$lt'):
                        #if k.endswith('at'): ???
                        v1 = datetime.strptime(v1, '%Y-%m-%d %H:%M:%S')
                    elif k1 == '$like':
                        k1 = '$regex'
                    c1.update({
                        k1: v1
                    })
                query_cond.update({
                    k: c1
                })
            else:
                query_cond.update({
                    k: v
                })
        else:
            query_cond.update({
                k: v
            })
    return query_cond


def paginator(query_dct):
    page = int(query_dct.get('$page', 1))
    size = int(query_dct.get('$size', 15))
    offset = (page - 1) * size
    return offset, size

if __name__ == '__main__':
    d = {u'channel_id': 57, u'start': u'{"$gte":"2018-04-01 00:00:00","$lt":"2018-04-12 00:00:00"}'}
    print parse_query(d)